// 监听页面加载
(function install() {
  // 等待页面加载完成
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', tryInsertButton);
  } else {
    tryInsertButton();
  }

  // 监听页面变化（因为BOSS直聘可能使用了动态加载）
  const observer = new MutationObserver(function (mutations) {
    // 检查是否需要重新插入按钮
    if (!document.querySelector('.hr-filter-btn')) {
      insertFilterButton();
    }
    // 如果过滤是激活的，对新加载的内容进行过滤
    chrome.storage.local.get(['filterOnlineOnly'], function (result) {
      if (result.filterOnlineOnly) {
        filterOfflineJobs();
      }
    });
  });

  // 开始观察页面变化
  observer.observe(document.body, {
    childList: true,
    subtree: true
  });

  console.log('直聘慧眼已加载！');
})();


// 修改等待元素的逻辑
function tryInsertButton() {
  if (!insertFilterButton()) { // 等待清空筛选按钮出现
    waitForElement('//a[@class="clear-search-btn"]').then(insertFilterButton);
  }
}

function getElementBySelector(selector) {
  // XPath or CSS Selector
  if (selector.startsWith('/')) {
    return document.evaluate(
      selector,
      document,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null
    ).singleNodeValue;
  } else {
    return document.querySelector(selector);
  }
}

// 等待元素出现的辅助函数
function waitForElement(selector) {
  return new Promise(resolve => {
    let element = getElementBySelector(selector);
    if (element) {
      return resolve(element);
    }

    const observer = new MutationObserver(mutations => {
      let element = getElementBySelector(selector);
      if (element) {
        observer.disconnect();
        resolve(element);
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  });
}

// 插入过滤按钮
function insertFilterButton() {
  ensure_inject_css();
  return addCheckBtn();

  function ensure_inject_css() {
    // 创建按钮样式
    if (!document.querySelector('#hr-filter-style')) {
      const style = document.createElement('style');
      style.id = 'hr-filter-style';
      style.textContent = `
      .hr-filter-btn {
        display: inline-block;
        margin-left: 10px;
        padding: 0 12px;
        height: 32px;
        line-height: 32px;
        color: #fff;
        background-color: #17b3af;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        border: none;
      }
      .hr-filter-btn.active {
        background-color: #c1c1c1;
      }`;
      document.head.appendChild(style);
    }
  }

  function addCheckBtn() {
    // 如果按钮已存在，则不重复创建
    if (document.querySelector('.hr-filter-btn')) {
      return true;
    }
    // 创建过滤按钮
    const filterBtn = document.createElement('button');
    filterBtn.className = 'hr-filter-btn';
    holdStatus(filterBtn);
    addClickListener(filterBtn);

    // 使用清空筛选条件按钮来定位
    const clearFilterBtn = getElementBySelector('//a[@class="clear-search-btn"]')
    if (!clearFilterBtn) {
      console.log('未找到清空筛选按钮，插入按钮失败');
      return false;
    } else {
      // 将按钮插入到清空筛选按钮的前边
      clearFilterBtn.parentNode.insertBefore(filterBtn, clearFilterBtn);
      return true
    }
  }

  function holdStatus(btn) {
    // 从storage获取之前的过滤状态
    chrome.storage.local.get(['filterOnlineOnly'], function (result) {
      if (result.filterOnlineOnly) {
        btn.classList.add('active');
        btn.textContent = '查看全部';
        filterOfflineJobs();
      } else {
        btn.textContent = '只看在线';
        showAllJobs();
      }
    });
  }
  function addClickListener(btn) {
    // 添加点击事件
    btn.addEventListener('click', function () {
      // 保存设置到storage
      chrome.storage.local.set({
        filterOnlineOnly: btn.classList.toggle('active')
      });
      holdStatus(btn);
    });
  }
}

function filterOfflineJobs() {
  // 过滤不在线的职位
  const jobs = document.querySelectorAll('.card-area .job-card-wrap');
  jobs.forEach(item => {
    // 查找在线标签
    const onlineTag = item.querySelector('.boss-online-icon');
    if (!onlineTag) {// 如果没有在线标签，则隐藏整个职位卡片
      item.style.display = 'none';
    }
  });
}

function showAllJobs() {
  // 显示所有职位
  const jobs = document.querySelectorAll('.card-area .job-card-wrap');
  jobs.forEach(item => {
    item.style.display = '';
  });
}